package edu.whu.powersoap;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import edu.whu.powersoap.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class PoiListActivity extends Activity implements OnScrollListener {

	private static final String TAG = "PoiListActivity";

	private Context mContext;
	private ListView mListView;
	private MapView mMapView;
	private BaiduMap mBaiduMap;
	private View moreView;
	private MyCursorAdapter adapter;
	private int count;
	private int lastItem;
	private int geoid0 = 21200;
	private int geoid1;
	private Cursor c;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = PoiListActivity.this;
		geoid1 = geoid0 +20;
		setContentView(R.layout.list_data);
		ContentResolver cr = mContext.getContentResolver();
		c = cr.query(PoiProvider.CONTENT_URI, new String[] {
				PoiProvider.VOLUMN_DEVICE_ID + " as _id",
				PoiProvider.VOLUMN_NAME, PoiProvider.VOLUMN_X,
				PoiProvider.VOLUMN_Y }, "geo_id >? AND geo_id <?", new String[]{String.valueOf(geoid0), String.valueOf(geoid1)}, null);
		count = c.getCount();
		adapter = new MyCursorAdapter(this, c);
		mListView = (ListView) findViewById(R.id.dataListView);
		moreView = getLayoutInflater().inflate(R.layout.load, null);
//		mMapView = (MapView) findViewById(R.id.dataMapView);
//		mBaiduMap = mMapView.getMap();

		mListView.addFooterView(moreView);
		mListView.setAdapter(adapter);
		
		mListView.setOnScrollListener(this);
		mListView.setOnItemClickListener(new OnItemClickListener() {
//			@Override
//			public void onItemClick(AdapterView<?> parent, View v,
//					int position, long id) {
//				PoiBean info = (PoiBean) v.getTag();
//				Log.d(TAG, "onItemClick poi=" + info);
//
//				BitmapDescriptor bd = BitmapDescriptorFactory
//						.fromResource(R.drawable.icon_gcoding);
//				LatLng ll = new LatLng(info.x, info.y);
//				OverlayOptions oo = new MarkerOptions().icon(bd).position(ll);
//				mBaiduMap.clear();
//				mBaiduMap.addOverlay(oo);
//				MapStatusUpdate u = MapStatusUpdateFactory
//						.newLatLngZoom(ll, 17);
//				mBaiduMap.animateMapStatus(u);
//			}

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				PoiBean info = (PoiBean) view.getTag();
				intent.putExtra("x", info.x);
				intent.putExtra("y", info.y);
                intent.setClass(PoiListActivity.this, BaseMapDemo.class);
                startActivity(intent);
                //设置切换动画，从右边进入，左边退出,带动态效果
                overridePendingTransition(R.layout.new_dync_in_from_right, R.layout.new_dync_out_to_left);
			}

		});

		
	}

	private void loadMoreData(){
		geoid1 = geoid1 + 5;
		mContext = PoiListActivity.this;
		ContentResolver cr = mContext.getContentResolver();
		c = cr.query(PoiProvider.CONTENT_URI, new String[] {
				PoiProvider.VOLUMN_DEVICE_ID + " as _id",
				PoiProvider.VOLUMN_NAME, PoiProvider.VOLUMN_X,
				PoiProvider.VOLUMN_Y }, "geo_id >? AND geo_id <?", new String[]{String.valueOf(geoid0), String.valueOf(geoid1)}, null);
		
		adapter = new MyCursorAdapter(this, c);
		mListView.setAdapter(adapter);
		count = c.getCount();
//		showHintDialog("test", String.valueOf(count));
		
	}
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		
		Log.i(TAG, "firstVisibleItem="+firstVisibleItem+"\nvisibleItemCount="+
				visibleItemCount+"\ntotalItemCount"+totalItemCount);
		
		lastItem = firstVisibleItem + visibleItemCount - 1;  //
		
	}

	public void onScrollStateChanged(AbsListView view, int scrollState) { 
		Log.i(TAG, "scrollState="+scrollState);
		//下拉到空闲时，进行更新
		if(lastItem == count && scrollState == OnScrollListener.SCROLL_STATE_IDLE){ 
			Log.i(TAG, "拉到最底部");
			moreView.setVisibility(View.VISIBLE);
		    mHandler.sendEmptyMessage(0);
			 
		}
		
	}
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:		     
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			    loadMoreData();
			    
			    adapter.notifyDataSetChanged();
			    moreView.setVisibility(View.GONE); 
			    
//			    if(count > 30){
//			    	Toast.makeText(PoiListActivity.this, "没有更多数据了", 3000).show();
//			          mListView.removeFooterView(moreView); 
//			    }
//				Log.i(TAG, "加载更多数据");
				break;
            case 1:
				
				break;
			default:
				break;
			}
		};
	};

	class MyCursorAdapter extends CursorAdapter {

		public MyCursorAdapter(Context context, Cursor c) {
			super(context, c);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater vi = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View view = vi.inflate(android.R.layout.simple_list_item_2, parent,
					false);
			return view;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			ViewGroup group = (ViewGroup) view;

			PoiBean poi = new PoiBean();

			poi.dev_id = cursor.getString(cursor.getColumnIndex("_id"));
			poi.name = cursor.getString(cursor
					.getColumnIndex(PoiProvider.VOLUMN_NAME));
			poi.x = cursor.getDouble(cursor
					.getColumnIndex(PoiProvider.VOLUMN_X));
			poi.y = cursor.getDouble(cursor
					.getColumnIndex(PoiProvider.VOLUMN_Y));

			TextView text1 = (TextView) group.findViewById(android.R.id.text1);
			TextView text2 = (TextView) group.findViewById(android.R.id.text2);
			text1.setText(poi.dev_id);
			text2.setText(poi.name);

			view.setTag(poi);

		}

	}
	private void showHintDialog(String title, String msg) {
		new AlertDialog.Builder(PoiListActivity.this).setTitle(title)
				.setMessage(msg)
				.setPositiveButton("确认", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).show();
	}

}
